<?php
namespace Admin\Model;
use Think\Model\RelationModel;

class StudentModel extends RelationModel {

	protected $_validate = array(
		array('id', 'require', '学号不能为空！', 1),
		array('id', 'number', '学号只能是数字！', 1),
		array('id', 'unique', '学号已存在！', 1, 'callback', 1),
		array('password', 'require', '密码不能为空！'),
		array('repassword', 'password', '两次输入的密码不一致！', 0, 'confirm'),
		array('name', 'require', '姓名不能为空！'),
		array('major_id', 'require', '专业不能为空！'),
		array('grade', 'require', '年级不能为空！'),
		array('class', 'require', '班号不能为空！'),
	);

	protected $_auto = array(
		array('password', '', 2, 'ignore'),
		array('password', 'handlePassword', 3, 'callback'),
	);

	protected $_link = array(
		'class' => array(
			'mapping_type'	=> self::BELONGS_TO,
			'class_name'	=> 'Class',
			'foreign_key'	=> 'class_id',
		),
		'logic_class_students'	=> array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'LogicClassStudent',
		    'foreign_key'   => 'student_id',
		),
	);

	protected function unique($id) {
		$result = $this->where(array('id' => $id))->find();
		return !$result;
	}

	protected function handlePassword($password) {
		return md5($password);
	}

	public function hasChildObj($id) {
		$result = $this->where(array('id' => $id))->relation('logic_class_students')->find();
		if($result['logic_class_students']) {
			$this->error = '该学生还有上课班级，请先从逻辑班级中删除该学生！';
			return true;
		}
		return false;
	}

}
